const express = require('express');
const config = require('../config/index');
const router = express.Router();
const db = require('../libs/db');
const axios = require('axios');

// 获取天气预报接口
router.get('/get-weather-report', async function(req, res, next) {
  try {
    const { city } = req.query;
    if(!city) {
      return res.json({
        code: -1,
        data: null,
        msg: '缺少城市名称'
      })
    }
    const sql = `SELECT districtcode,city
                        FROM weather_district
                        WHERE city = ?
                        OR district = ?`;
    const row = db.prepare(sql).get(city,city);
    if(!row) {
      return res.json({
        code: -1,
        data: null,
        msg: '未能查询该城市天气信息'
      })
    }
    const { data } = await axios.get('https://api.map.baidu.com/weather/v1/', {
      params: {
        district_id: row?.districtcode,
        data_type: 'all',
        ak: config.ak,
      }
    })
    if(data.status === 0) {
      res.json({
        code: 0,
        data: data.result
      });
    } else {
      console.log(data);
      res.json({
        code: -1,
        data: null,
        msg: '获取天气失败'
      })
    }
  } catch (e) {
    res.json({
      code: -1,
      data: null,
      msg: '服务器异常'
    })
  }
});

module.exports = router;
